<template>
  <div class="model-list-container">
    <div class="page-header">
      <h2>模型管理</h2>
      <div class="actions">
        <el-button type="primary" @click="showCreateModelDialog">
          <el-icon><Plus /></el-icon>训练新模型
        </el-button>
        <el-button @click="refreshModels">
          <el-icon><Refresh /></el-icon>刷新列表
        </el-button>
      </div>
    </div>

    <!-- 模型指标卡片 -->
    <el-card class="metrics-card" v-loading="loadingMetrics">
      <template #header>
        <div class="card-header">
          <h3>模型性能指标</h3>
        </div>
      </template>
      <div v-if="!metrics.count" class="empty-metrics">
        <el-empty description="暂无模型数据" />
      </div>
      <div v-else class="metrics-grid">
        <div class="metric-item">
          <div class="metric-value">{{ metrics.count }}</div>
          <div class="metric-label">已训练模型</div>
        </div>
        <div class="metric-item">
          <div class="metric-value">{{ (metrics.average_accuracy * 100).toFixed(2) }}%</div>
          <div class="metric-label">平均准确率</div>
        </div>
        <div class="metric-item" v-if="metrics.best_model">
          <div class="metric-value">{{ metrics.best_model.name }}</div>
          <div class="metric-label">最佳模型 ({{ (metrics.best_model.accuracy * 100).toFixed(2) }}%)</div>
          <el-tag v-if="metrics.best_model.is_active" size="small" type="success">当前激活</el-tag>
        </div>
      </div>
    </el-card>

    <!-- 模型列表 -->
    <div class="model-filter">
      <el-form :inline="true" class="filter-form">
        <el-form-item label="模型类型">
          <el-select v-model="filters.model_type" placeholder="全部" clearable>
            <el-option v-for="type in modelTypeOptions" :key="type.value" :label="type.label" :value="type.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filters.status" placeholder="全部" clearable>
            <el-option label="训练中" value="training" />
            <el-option label="已完成" value="completed" />
            <el-option label="失败" value="failed" />
          </el-select>
        </el-form-item>
        <el-form-item label="最低准确率">
          <el-slider 
            v-model="filters.min_accuracy" 
            :min="0" 
            :max="1" 
            :step="0.05" 
            :show-tooltip="true"
            :format-tooltip="value => `${(value * 100).toFixed(0)}%`"
            style="width: 200px;"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="filterModels">筛选</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <el-row :gutter="20" class="model-list" v-loading="loading">
      <el-col v-if="models.length === 0 && !loading" :span="24">
        <el-empty description="暂无模型数据，请创建新模型" />
      </el-col>
      <el-col v-for="model in models" :key="model.id" :xs="24" :sm="12" :md="8" :lg="6">
        <el-card 
          class="model-card"
          :class="{ 'is-active': model.is_active }" 
          shadow="hover"
        >
          <div class="model-card-header">
            <h3>{{ model.name }}</h3>
            <el-tag v-if="model.is_active" size="small" type="success">当前激活</el-tag>
          </div>
          <div class="model-info">
            <div class="info-item">
              <span class="label">模型类型:</span>
              <span class="value">{{ model.model_type_display }}</span>
            </div>
            <div class="info-item">
              <span class="label">状态:</span>
              <span class="value">
                <el-tag :type="getStatusType(model.status)" size="small">
                  {{ model.status_display }}
                </el-tag>
              </span>
            </div>
            <div class="info-item" v-if="model.status === 'completed'">
              <span class="label">准确率:</span>
              <span class="value">{{ (model.accuracy * 100).toFixed(2) }}%</span>
            </div>
            <div class="info-item">
              <span class="label">创建时间:</span>
              <span class="value">{{ model.created_at_formatted }}</span>
            </div>
          </div>
          <div class="model-actions">
            <el-button-group>
              <el-button size="small" @click="viewModelDetail(model.id)">详情</el-button>
              <el-button 
                size="small" 
                type="success" 
                v-if="model.status === 'completed' && !model.is_active"
                @click="activateModel(model.id)"
              >激活</el-button>
              <el-button size="small" type="danger" @click="confirmDeleteModel(model.id)">删除</el-button>
            </el-button-group>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-pagination
      v-if="total > 0"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[8, 12, 24, 36]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      background
      class="pagination"
    />

    <!-- 创建模型对话框 -->
    <el-dialog
      v-model="createModelDialogVisible"
      title="创建新模型"
      width="580px"
      @close="resetCreateModelForm"
    >
      <el-form
        ref="modelForm"
        :model="modelForm"
        :rules="modelFormRules"
        label-width="100px"
        label-position="top"
      >
        <el-form-item label="模型名称" prop="name">
          <el-input v-model="modelForm.name" placeholder="给模型起个名字" />
        </el-form-item>
        <el-form-item label="模型类型" prop="model_type">
          <el-select v-model="modelForm.model_type" placeholder="选择模型类型" style="width: 100%">
            <el-option 
              v-for="type in modelTypeOptions" 
              :key="type.value" 
              :label="type.label" 
              :value="type.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="模型描述" prop="description">
          <el-input 
            v-model="modelForm.description" 
            type="textarea" 
            rows="3"
            placeholder="模型描述（可选）" 
          />
        </el-form-item>
        <el-divider>高级选项</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否使用SMOTE平衡数据" prop="use_smote">
              <el-switch v-model="modelForm.use_smote" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否使用特征选择" prop="use_feature_selection">
              <el-switch v-model="modelForm.use_feature_selection" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="测试集比例" prop="test_size">
          <el-slider 
            v-model="modelForm.test_size" 
            :min="0.1" 
            :max="0.5" 
            :step="0.05"
            :format-tooltip="value => `${(value * 100).toFixed(0)}%`"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createModelDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitModelForm" :loading="submitting">开始训练</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh } from '@element-plus/icons-vue'
import { getModels, getModelTypes, trainModel, activateModel as activateModelApi, deleteModel, getModelMetrics } from '@/api/modules/models'

const router = useRouter()

// 页面状态
const loading = ref(false)
const loadingMetrics = ref(false)
const submitting = ref(false)
const models = ref([])
const modelTypeOptions = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(12)
const metrics = ref({
  count: 0,
  average_accuracy: 0,
  best_model: null,
  model_types: [],
  accuracy_over_time: []
})

// 创建模型对话框
const createModelDialogVisible = ref(false)
const modelForm = reactive({
  name: '',
  model_type: '',
  description: '',
  use_smote: true,
  use_feature_selection: true,
  test_size: 0.2,
  hyperparameters: {}
})
const modelFormRules = {
  name: [
    { required: true, message: '请输入模型名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  model_type: [
    { required: true, message: '请选择模型类型', trigger: 'change' }
  ]
}
const modelFormRef = ref(null)

// 筛选条件
const filters = reactive({
  model_type: '',
  status: '',
  min_accuracy: 0
})

// 计算属性
const getStatusType = (status) => {
  switch (status) {
    case 'training':
      return 'warning'
    case 'completed':
      return 'success'
    case 'failed':
      return 'danger'
    default:
      return 'info'
  }
}

// 生命周期钩子
onMounted(async () => {
  // 加载模型类型选项
  await loadModelTypes()
  // 加载模型列表
  await fetchModels()
  // 加载模型指标
  await fetchModelMetrics()
})

// 方法
const loadModelTypes = async () => {
  try {
    const { data } = await getModelTypes()
    modelTypeOptions.value = data
  } catch (error) {
    console.error('获取模型类型失败', error)
    ElMessage.error('获取模型类型失败')
  }
}

const fetchModels = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      page_size: pageSize.value,
      ...filters
    }
    
    const res = await getModels(params)
    models.value = res.results
    total.value = res.count
  } catch (error) {
    console.error('获取模型列表失败', error)
    ElMessage.error('获取模型列表失败')
  } finally {
    loading.value = false
  }
}

const fetchModelMetrics = async () => {
  loadingMetrics.value = true
  try {
    const res = await getModelMetrics()
    metrics.value = res
  } catch (error) {
    console.error('获取模型指标失败', error)
  } finally {
    loadingMetrics.value = false
  }
}

const showCreateModelDialog = () => {
  createModelDialogVisible.value = true
}

const resetCreateModelForm = () => {
  if (modelFormRef.value) {
    modelFormRef.value.resetFields()
  }
  
  modelForm.name = ''
  modelForm.model_type = ''
  modelForm.description = ''
  modelForm.use_smote = true
  modelForm.use_feature_selection = true
  modelForm.test_size = 0.2
  modelForm.hyperparameters = {}
}

const submitModelForm = async () => {
  if (modelFormRef.value) {
    await modelFormRef.value.validate(async (valid) => {
      if (valid) {
        submitting.value = true
        try {
          await trainModel({
            name: modelForm.name,
            model_type: modelForm.model_type,
            description: modelForm.description,
            use_smote: modelForm.use_smote,
            use_feature_selection: modelForm.use_feature_selection,
            test_size: modelForm.test_size,
            hyperparameters: modelForm.hyperparameters
          })
          
          ElMessage.success('模型训练已开始')
          createModelDialogVisible.value = false
          await fetchModels()
          await fetchModelMetrics()
        } catch (error) {
          console.error('创建模型失败', error)
          ElMessage.error('创建模型失败: ' + (error.response?.data?.error || '未知错误'))
        } finally {
          submitting.value = false
        }
      }
    })
  }
}

const activateModel = async (modelId) => {
  try {
    await activateModelApi(modelId)
    ElMessage.success('模型已激活')
    await fetchModels()
    await fetchModelMetrics()
  } catch (error) {
    console.error('激活模型失败', error)
    ElMessage.error('激活模型失败: ' + (error.response?.data?.error || '未知错误'))
  }
}

const confirmDeleteModel = (modelId) => {
  ElMessageBox.confirm('此操作将永久删除该模型, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteModel(modelId)
      ElMessage.success('删除成功')
      await fetchModels()
      await fetchModelMetrics()
    } catch (error) {
      console.error('删除模型失败', error)
      ElMessage.error('删除模型失败: ' + (error.response?.data?.error || '未知错误'))
    }
  }).catch(() => {})
}

const viewModelDetail = (modelId) => {
  router.push(`/models/${modelId}`)
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchModels()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchModels()
}

const filterModels = () => {
  currentPage.value = 1
  fetchModels()
}

const resetFilters = () => {
  filters.model_type = ''
  filters.status = ''
  filters.min_accuracy = 0
  filterModels()
}

const refreshModels = async () => {
  await fetchModels()
  await fetchModelMetrics()
}
</script>

<style lang="scss" scoped>
.model-list-container {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      font-weight: 500;
    }
    
    .actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .metrics-card {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 500;
      }
    }
    
    .metrics-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 20px;
      
      .metric-item {
        text-align: center;
        
        .metric-value {
          font-size: 28px;
          font-weight: 600;
          margin-bottom: 5px;
        }
        
        .metric-label {
          font-size: 14px;
          color: #666;
        }
      }
    }
    
    .empty-metrics {
      height: 150px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  
  .model-filter {
    margin-bottom: 20px;
  }
  
  .model-list {
    margin-bottom: 20px;
    
    .model-card {
      height: 100%;
      margin-bottom: 20px;
      transition: all 0.3s ease;
      
      &.is-active {
        border: 1px solid #67C23A;
        box-shadow: 0 0 10px rgba(103, 194, 58, 0.2);
      }
      
      .model-card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
        
        h3 {
          margin: 0;
          font-size: 16px;
          font-weight: 500;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
      
      .model-info {
        margin-bottom: 15px;
        
        .info-item {
          display: flex;
          justify-content: space-between;
          margin-bottom: 5px;
          
          .label {
            color: #666;
            font-size: 14px;
          }
          
          .value {
            font-size: 14px;
            font-weight: 500;
          }
        }
      }
      
      .model-actions {
        text-align: right;
      }
    }
  }
  
  .pagination {
    margin-top: 20px;
    text-align: center;
  }
}
</style> 